define(['../../common/service'], function (http) {
    var createAdword =  {
        init: function () {
            this.bindBackEvent();		//绑定新建用户返回事件
            this.bindKeyUpEvent();		//绑定键盘收起事件【用于计算广告词字数、对阿拉伯语言进行特殊处理】
            //this.initSelect2ToTabs();	//初始化标签为select2插件
            this._initAppSelect(); 		//初始化应用数据
            this._initLanguageSelect();  //初始化语言
            this.bindSubmitEvent();		//绑定新建用户提交事件
        }
        /*
         @绑定键盘收起事件【用于计算广告词字数、对阿拉伯语言进行特殊处理】
         */
        , bindKeyUpEvent: function () {
            var _area = $('textarea'),//字符串数字监控区:广告语和备注
                _len = '';
            _area.unbind("input");
            _area.bind("input", function () {
                var maxLength = $(this).attr('maxlength');
                var stringNumber = $(this).parent().find('.stringNumber');   //字符串数字显示区
                if (!stringNumber || stringNumber.length == 0) {
                    console.log('绑定键盘收起事件【用于计算广告词字数】时未捕获有效的DOM节点，已跳出');
                    return false;
                }
                _len = this.value.length;
                if(_len < 90){
                    stringNumber.text(I18N.getText('createAdword','inputCharPre', (maxLength-_len))+I18N.getText('createAdword','inputCharPost'));
                }
                else if(_len>90 && _len< maxLength){
                	 stringNumber.text(I18N.getText('createAdword','showWordMsg'));
                }
                else if(_len >= maxLength){
                    stringNumber.text(I18N.getText('createAdword','maxlength'));
                }
                if (_isAr(this.value)) {
                    $(this).attr('dir', 'rtl');
                } else {
                    $(this).removeAttr('dir', 'rtl');
                }
            });

            //验证是否为阿拉伯语言
            function _isAr(str) {
                //判断文字中是否含有阿拉伯语
                for (var i = 0; i < str.length; i++) {
                    var code = str.charCodeAt(i);
                    if (code > 0x600 && code < 0x6ff) {
                        return true;
                    }
                    if (code > 0xFE70 && code < 0xFEFF) {
                        return true;
                    }
                }
                return false;
            }
        }
        /*
         @绑定新建用户提交事件
         含表单验证
         */
        , bindSubmitEvent: function () {
            var _this = this;
            var myForm = $('#myForm');
            var submitForm = myForm.find('.submitForm');
            var appArea = $('.app-area', myForm),
                languageArea = $('.language-area', myForm),
            //tags 	= myForm.find('input[name=tags]'),			//标签
                adWords = myForm.find('textarea[name=adWords]'),    //广告词
                remark = myForm.find('textarea[name=remark]');	    //备注

            //清除缓存
            //tags.select2('data',[]);
            adWords.val('');
            remark.val('');
            //绑定事件
            submitForm.unbind('click');
            submitForm.click(function () {
                //校验
                var _selectedApp = appArea.select2('data')[0];
                if (-1 == _selectedApp.id || '' == _selectedApp.id) {
                    kit.alert2(I18N.getText('createAdword','selectApp'));
                    return false;
                }

                var _selectedLanguage = languageArea.select2('data')[0];
                if (-1 == _selectedLanguage.id || '' == _selectedLanguage.id) {
                    kit.alert2(I18N.getText('createAdword','selectLanguage'));
                    return false;
                }

                if ($.trim(adWords.val()) == '') {
                    kit.alert2(I18N.getText('createAdword','inputAdword'));
                    adWords.focus();
                    return false;
                }
                var par = {
                    //tags					: tags.val()	|| '',
                    word: adWords.val() || '',
                    fbConnectionObjectId: _selectedApp.id,
                    fbConnectionObjectName: _selectedApp.text || '',
                    languageId: _selectedLanguage.id,                          //语言Id
                    language: _selectedLanguage.text || '',                 //语言
                    description: remark.val() || ''
                };

                http.do("/adwords/createAdword",
                    {param: JSON.stringify(par)}).then(function (res) {
                    	if(res.flag == 'success'){
                    		 kit.alert_success(I18N.getText('createAdword','createSucceed'));
	                        //tags.select2('data',[]);
	                        adWords.val('');
	                        adWords.trigger("input");
	                        remark.val('');
	                        remark.trigger("input");
                    	}else{
                    		kit.alert2(res.msg || I18N.getText('createAdword','createFail'));
                    	}
                    });
            });
        }
        , _initAppSelect: function () {
            var _this = this;
            var appArea = $('.app-area');
            var par = {
                typeId: 2  //1、主页; 2、应用
            };
            var loadArea = appArea.closest('div');
            kit.loading.show(loadArea);
            http.do("/connectionobjects/searchAppsAndConfigurations",
                {param: JSON.stringify(par)}).then(function (res) {
                    //data = _.sortBy(data,function (item) {return item.name.toLowerCase();});
                    var tmpHtml = '<option value="-1">'+I18N.getText('createAdword','selectApp')+'</option>';
                    for (var i = 0; i < res.data.length; i++) {
                        tmpHtml += '<option value="' + (res.data[i].fbConnectionObjectId || '') + '">'
                            + res.data[i].name
                            + '</option>'
                    }
                    appArea.html(tmpHtml);
                    appArea.select2();
                    $('select[name="app"]').trigger("change");
                    kit.loading.hide(loadArea);
                });
        }
        , _initLanguageSelect: function () {
            var self = this;

            var languageArea = $('.language-area'),
                selectLanguage = $('.select-language');
            var par = {
                "type": "adword"
            };
            var loadingArea = languageArea.closest('div');
            kit.loading.show(loadingArea);
            http.do("/search/getDictionary",
                {param: JSON.stringify(par)}).then(function (res) {
                    var data = res.data;
                    var tmpHtml = '<option value="-1">'+I18N.getText('createAdword','selectLanguage')+'</option>';
                    $.each(data, function (index, dict) {
                        tmpHtml += '<option value="' + (dict.id || '') + '">'
                            + dict.name
                            + '</option>'
                    });
                    languageArea.html(tmpHtml);
                    languageArea.select2({
                        minimumResultsForSearch: Infinity
                    });
                    kit.loading.hide(loadingArea);
                }, function () {
                    kit.alert2(I18N.getText('createAdword','createFail'));
                });
        }
        /*
         @绑定用户返回事件
         */
        , bindBackEvent: function () {
            var myForm = $('#myForm');
            var goBack = myForm.find('.goBack');
            goBack.unbind('click');
            goBack.click(function () {
                window.location.hash = '#!adwords';
            });
        }
        ,dispose: function () {

        }
    }
    return createAdword;
})
